package org.nowcoder.leetcode.BTree;

/**
 * Title  : 129. Sum Root to Leaf Numbers
 * Source : https://leetcode.cn/problems/sum-root-to-leaf-numbers/description/?envType=study-plan-v2&envId=top-interview-150
 * Author : XrazYang
 * Date   : 2023-09-09
 */

public class LeetCode_129 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int sumNumbers(TreeNode root) {
        //非递归的实现
        // ArrayDeque<TreeNode> sta = new ArrayDeque<>(); //深度优先遍历

        // int sum = 0;
        // Deque<Integer> deque = new ArrayDeque<>(); //双端队列,保存结果
        // sta.push(root);
        // deque.offerLast(root.val);
        // while (!sta.isEmpty()) {
        //     TreeNode node = sta.pop();
        //     int i = deque.pollLast();
        //     if (node.left == null && node.right == null) {
        //         sum += i;
        //     }
        //     if (node.left != null) {
        //         sta.push(node.left);
        //         deque.offerLast(i * 10 + node.left.val);
        //     }
        //     if (node.right != null) {
        //         sta.push(node.right);
        //         deque.offerLast(i * 10 + node.right.val);
        //     }
        // }
        // return sum;

        //递归实现
        return dfs(root,0);
    }

    public  int dfs(TreeNode root, int sum) {
        if (root != null) {
            sum = sum * 10 + root.val;
            if (root.left == null && root.right == null) {
                return sum ;
            }
            return dfs(root.left, sum) + dfs(root.right, sum);
        }
        return 0;
    }
}
